# 自定义用户认证后端步骤:
#
# 在 users 应用中新建 utils.py 文件
# 新建类，继承自 ModelBackend
# 重写认证 authenticate( ) 方法
# 分别使用用户名和手机号查询用户
# 返回查询到的用户实例
import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def get_user_by_account(username):
    try:
        if re.match('^1[3-9]\d{9}$', username):
            user = User.objects.get(mobile = username)
        else:
            user = User.objects.get(username=username)
    except Exception as e:
        return None
    else:
        return user


class mobie_model(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)
        if user and user.check_password(password):
            return user




